﻿using UnityEngine;

namespace BToolkit
{
    [ExecuteInEditMode]
    public class BoxLayoutGroup : MonoBehaviour
    {
        public RectTransform cell;
        public Vector2 cellSize = new Vector2(200, 150);
        public Vector2 spaces = new Vector2(0, 0);
        public int horSize = 5;
        public int colSize = 5;

        private void Update()
        {
            if (horSize < 2)
            {
                horSize = 2;
            }
            if (colSize < 2)
            {
                colSize = 2;
            }
            int total = horSize * 2 + (colSize - 2) * 2;
            if (!cell) return;
            if (transform.childCount < total)
            {
                for (int i = 0; i < total - 1; i++)
                {
                    RectTransform _cell = i == 0 ? cell : Instantiate(cell);
                    _cell.SetParent(cell.parent, false);
                    if (transform.childCount == total)
                    {
                        SetNames();
                        break;
                    }
                }
                SetNames();
            }
            else if (transform.childCount > total)
            {
                for (int i = 0; i < transform.childCount; i++)
                {
                    if (i >= total)
                    {
                        Transform trans = transform.GetChild(i);
                        if (trans) DestroyImmediate(trans.gameObject);
                    }
                }
            }
            float totalW = horSize * cellSize.x + (horSize - 1) * spaces.x;
            float totalH = colSize * cellSize.y + (colSize - 1) * spaces.y;
            Vector2 pos;
            pos.x = -totalW * 0.5f + cellSize.x * 0.5f;
            pos.y = totalH * 0.5f - cellSize.y * 0.5f;
            for (int i = 0; i < transform.childCount; i++)
            {
                RectTransform cell = transform.GetChild(i) as RectTransform;
                cell.sizeDelta = cellSize;
                if (i < horSize - 1)
                {
                    pos.x += cellSize.x + spaces.x;
                }
                else if (i < horSize + colSize - 2)
                {
                    pos.y -= cellSize.y + spaces.y;
                }
                else if (i < horSize + colSize - 3 + horSize)
                {
                    pos.x -= cellSize.x + spaces.x;
                }
                else
                {
                    pos.y += cellSize.y + spaces.y;
                }
                cell.anchoredPosition = pos;
            }
        }

        void SetNames()
        {
            for (int i = 0; i < transform.childCount; i++)
            {
                transform.GetChild(i).name = "Cell_" + (i + 1);
            }
        }
    }
}